package com.dfkj.wmswcs.service;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dfkj.wmswcs.common.BaseResponse;
import com.dfkj.wmswcs.common.ErrorCode;
import com.dfkj.wmswcs.common.ResultUtils;
import com.dfkj.wmswcs.exception.BusinessException;
import com.dfkj.wmswcs.exception.ThrowUtils;
import com.dfkj.wmswcs.mapper.*;
import com.dfkj.wmswcs.model.domain.*;
import com.dfkj.wmswcs.model.dto.*;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Log4j2
@Service
public class WmsToWcsService {

    @Value("${wcs.api.url}")
    private String baseUrl;

    @Resource
    private WsTaskMapper taskMapper;

    @Resource
    private WmConveyTaskMapper conveyTaskMapper;

    @Resource
    private WcsBarCodeMapper wcsBarCodeMapper;

    @Resource
    private WcsPalletMapper wcsPalletMapper;

    @Resource
    private WcsPalletNumberMapper palletNumberMapper;

    @Resource
    private WcsPointMapper wcsPointMapper;

    @Resource
    private WcsLocationMapper wcsLocationMapper;


    @Transactional
    public BaseResponse setStackerTask() {


        QueryWrapper<WsTask> wrapper = new QueryWrapper<>();
        //只查询状态为0的
        wrapper.eq("status", 0);
        List<WsTask> wsTasks = taskMapper.selectList(wrapper);
        if (wsTasks.isEmpty()) {
            log.info("无推送任务最新数据");
            return ResultUtils.success("暂无新数据");
        }

        ArrayList<WmsTaskDto> taskDtos = new ArrayList<>();
        for (WsTask wsTask : wsTasks) {
            WmsTaskDto wmsTaskDto = new WmsTaskDto();
            BeanUtils.copyProperties(wsTask, wmsTaskDto);
            taskDtos.add(wmsTaskDto);
            wsTask.setStatus(1);
            taskMapper.updateById(wsTask);
        }
        String body = JSONUtil.toJsonStr(taskDtos);

        log.info("推送任务请求参数{},接口地址/api/wms/stacker/setStackerTask", body);

        //调用WCS接口
        HttpResponse response = HttpRequest.post(baseUrl + "/api/wms/stacker/setStackerTask").body(body).execute();
        String resp = response.body();

        JSONObject respObj = JSONUtil.parseObj(resp);

        log.info("推送任务响应{}", respObj);
        Integer respCode = (Integer) respObj.get("code");

        if (respCode == 0) {

            return ResultUtils.success(respObj.get("returnData"));
        }
        return ResultUtils.error(500, "创建任务失败");


    }


    public BaseResponse changeTaskStatus(WmsTaskChangeDto changeDto) {

        String body = JSONUtil.toJsonStr(changeDto);
        log.info("更改任务状态请求参数{},接口地址/api/wms/stacker/changeTaskStatus", body);
        //调用WCS接口
        HttpResponse response = HttpRequest.post(baseUrl + "/api/wms/stacker/changeTaskStatus").body(body).execute();
        String resp = response.body();
        JSONObject respObj = JSONUtil.parseObj(resp);
        log.info("更改任务状态响应{}", respObj);
        Integer respCode = (Integer) respObj.get("code");

        if (respCode == 0) {
            return ResultUtils.success("修改任务状态成功");
        }
        return ResultUtils.error(1, "修改任务状态失败");

    }


    public BaseResponse wcsUpdateWms(WcsTaskChangeDto changeDto) {

        String taskId = changeDto.getTaskId();
        WsTask wsTask = taskMapper.selectById(taskId);
        if (wsTask == null) {
            return ResultUtils.error(1, "taskId不存在");
        }

        //更新任务状态信息
        wsTask.setTaskStatus(changeDto.getTaskStatus());
        wsTask.setDestination(changeDto.getDestination());
        wsTask.setMessage(changeDto.getMessage());
        taskMapper.updateById(wsTask);
        return ResultUtils.success("成功");
    }

    public BaseResponse wcsRequestwarehouse(WcsRequestWarehoseDto dto) {

        WcsPoint wcsPoint = new WcsPoint();
        BeanUtils.copyProperties(dto, wcsPoint);
        wcsPoint.setStatus(0);
        wcsPointMapper.insertOrUpdate(wcsPoint);
        HashMap<String, Object> data = new HashMap<>();
        data.put("inStand", dto.getPoint());
        data.put("remark", "");
        return ResultUtils.success(data);


    }

    public BaseResponse setStackerTaskNewDestination(WmsTaskNewDestinationDto dto) {
        String body = JSONUtil.toJsonStr(dto);

        log.info("WMS向WCS推送新的目的地请求参数{},接口地址/api/wms/stacker/setStackerTaskNewDestination", body);
        //调用WCS接口
        HttpResponse response = HttpRequest.post(baseUrl + "/api/wms/stacker/setStackerTaskNewDestination").body(body).execute();
        String resp = response.body();
        JSONObject respObj = JSONUtil.parseObj(resp);
        log.info("推送新的目的地{}", respObj);
        Integer respCode = (Integer) respObj.get("code");

        if (respCode == 0) {
            return ResultUtils.success("设置新任务终点成功");
        }
        return ResultUtils.error(500, "设置新任务终点失败");

    }


    public BaseResponse setConveryTask(WmsConveyTaskDto conveyTaskDto) {


        String body = JSONUtil.toJsonStr(conveyTaskDto);
        log.info("推送箱式线任务请求参数{},接口地址/api/wms/stacker/setConveyTask", body);
        //调用WCS接口
        HttpResponse response = HttpRequest.post(baseUrl + "/api/wms/convey/setConveyTask").body(body).execute();
        String resp = response.body();
        JSONObject respObj = JSONUtil.parseObj(resp);
        log.info("推送箱式线任务响应{}", respObj);
        Integer respCode = (Integer) respObj.get("code");

        if (respCode == 0) {
            return ResultUtils.success("请求成功");
        }
        return ResultUtils.error(500, "请求失败，当前任务未全部完结");


    }

    public BaseResponse wcsComeLocation(WcsConveyTaskChangeDto changeDto) {

        QueryWrapper<WmConveyTask> wrapper = new QueryWrapper<>();
        wrapper.eq("taskGroup", changeDto.getTaskGroup());

        WmConveyTask wmConveyTask = conveyTaskMapper.selectOne(wrapper);
        BeanUtils.copyProperties(changeDto, wmConveyTask);
        wmConveyTask.setStatus(0);
        conveyTaskMapper.insertOrUpdate(wmConveyTask);

        return ResultUtils.success("请求成功");


    }

    public BaseResponse releaseBox(LocationDto dto) {

        WcsLocation wcsLocation = new WcsLocation();
        BeanUtils.copyProperties(dto, wcsLocation);
        wcsLocation.setStatus(0);
        wcsLocationMapper.insertOrUpdate(wcsLocation);

        return ResultUtils.success("操作成功");
    }


    @Transactional
    public BaseResponse wmsToWcsBarCode() {

        QueryWrapper<WcsBarCode> wrapper = new QueryWrapper<>();
        wrapper.eq("status", 0);
        List<WcsBarCode> wcsBarCodes = wcsBarCodeMapper.selectList(wrapper);

        ArrayList<WcsBarCodeDto> dtos = new ArrayList<>();
        for (WcsBarCode barCode : wcsBarCodes) {
            WcsBarCodeDto barCodeDto = new WcsBarCodeDto();
            barCodeDto.setBarCode(barCode.getBarCode());
            barCodeDto.setGoodsId(barCode.getGoodsId());
            barCodeDto.setGoodsName(barCode.getGoodsName());
            barCodeDto.setGoodsNum(barCode.getGoodsNum());
            barCodeDto.setBatchNum(barCode.getBatchNum());
            barCodeDto.setBoxLength(barCode.getBoxLength());
            barCodeDto.setBoxWidth(barCode.getBoxWidth());
            barCodeDto.setBoxHeight(barCode.getBoxHeight());
            barCodeDto.setPort(barCode.getPort());
            dtos.add(barCodeDto);
        }

        if (wcsBarCodes.isEmpty()) {
            log.info("无最新推送箱码信息数据");
            return ResultUtils.success("无最新推送箱码信息数据");
        }
        String body = JSONUtil.toJsonStr(dtos);

        log.info("推送箱数据请求参数为{},接口路径为{}", body, "/api/wms/WmsToWcsBarCode");
        //调用WCS接口
        HttpResponse response = HttpRequest.post(baseUrl + "/api/wms/WmsToWcsBarCode").body(body).execute();
        String resp = response.body();
        JSONObject respObj = JSONUtil.parseObj(resp);

        log.info("推送箱数据响应为{}", respObj);
        Integer respCode = (Integer) respObj.get("code");


        if (respCode == 0) {
            for (WcsBarCode wcsBarCode : wcsBarCodes) {
                wcsBarCode.setStatus(1);
                wcsBarCodeMapper.updateById(wcsBarCode);
            }
            return ResultUtils.success("请求成功");
        }
        return ResultUtils.error(500, "请求失败");

    }


    public BaseResponse boxFinish(List<WcsPalletDto> pallets) {

        for (WcsPalletDto pallet : pallets) {

            WcsPallet wcsPallet = new WcsPallet();
            wcsPallet.setPalletId(pallet.getPalletId());
            wcsPallet.setBarcode(pallet.getBarCode());
            wcsPallet.setStatus(0);

            wcsPalletMapper.insertOrUpdate(wcsPallet);
        }

        return ResultUtils.success("操作成功");
    }


    public BaseResponse emptyPalletNumber(WcsPalletNumberDto palletNumberDto) {

        WcsPalletNumber number = new WcsPalletNumber();
        number.setStatus(0);
        number.setPalletNumber(palletNumberDto.getPalletNumber());
        palletNumberMapper.insertOrUpdate(number);

        return ResultUtils.success("操作成功");
    }
}
